<script lang="ts">
// 质检项
export default {
  name: "inspectionItem",
  components: { uploadExcel }
};
</script>

<script setup lang="ts">
import { reactive, ref, nextTick, onMounted } from "vue";
import { changeHeight } from "/@/utils/public.mixin";
import {
  VXETable,
  VxeTableInstance,
  VxeFormPropTypes,
  VxeFormInstance
} from "vxe-table";
import {
  addQualityInItem,
  updateQualityInItem,
  disabledQualityInItemById,
  queryQualityInItemPage,
  downloadTemplete
} from "/@/api/quality/inspectionItem";
import { successMessage, errorMessage } from "/@/utils/message";
import { useRoute } from "vue-router";
import uploadExcel from "/@/components/uploadExcel/index.vue"; //导入文件
const route = useRoute();
const routeName = route.name as string;
const page = reactive({
  pageNum: 1,
  pageRow: 20,
  totalResult: 0
});
const table = reactive({
  loading: false,
  tableData: [] as any[],
  tableHeight: 0, //表格高度
  listQuery: {
    filterName: ""
  }
});

const xTable = ref({} as VxeTableInstance);
const xForm = ref({} as VxeFormInstance);
// 查询
const searchEvent = () => {
  const data: any = {};
  data.name = table.listQuery.filterName;
  data.pageNum = page.pageNum;
  data.pageRow = page.pageRow;
  table.loading = true;
  queryQualityInItemPage(data).then((res: any) => {
    if (res.code === 0) {
      table.tableData = res.data.list;
      page.totalResult = res.data.total;
    }
    table.loading = false;
  });
};
// 分页发生改变时会触发该事件
const handlePageChange = ({ currentPage, pageSize }) => {
  page.pageNum = currentPage;
  page.pageRow = pageSize;
  searchEvent();
};
const procedure = reactive({
  loading: false,
  submitLoading: false,
  filterName: "",
  selectRow: null,
  showEdit: false,
  tableData: [] as any[],
  formData: {
    id: -1,
    name: "",
    standard: "",
    specificity: "",
    measureTools: "",
    recordForm: "",
    selfTest: 1 as any,
    qiTest: 1 as any
  },
  formRules: {
    name: [{ required: true, message: "请输入检查项目" }]
  } as VxeFormPropTypes.Rules
});

// 修改
const editEvent = (row: any) => {
  procedure.formData = {
    id: row.id,
    name: row.name,
    standard: row.standard,
    specificity: row.specificity,
    measureTools: row.measureTools,
    recordForm: row.recordForm,
    selfTest: row.selfTest,
    qiTest: row.qiTest
  };
  procedure.selectRow = row;
  procedure.showEdit = true;
};
// 禁用
const disableEvent = async (row: any) => {
  let message = "";
  if (row.isEnabled == 0) {
    message = "启用";
  } else {
    message = "禁用";
  }
  const type = await VXETable.modal.confirm(
    "您确定要" + message + "该检查项目?"
  );
  if (type === "confirm") {
    disabledQualityInItemById(row.id).then((res: any) => {
      if (res.code === 0) {
        successMessage(message + "检查项目成功");
        searchEvent();
      } else {
        errorMessage(res.message);
      }
    });
  }
};
// 新增
const insertEvent = () => {
  procedure.formData = {
    id: -1,
    name: "",
    standard: "",
    specificity: "",
    measureTools: "",
    recordForm: "",
    selfTest: 1 as any,
    qiTest: 1 as any
  };
  procedure.selectRow = null;
  procedure.showEdit = true;
};

// 表单提交
const submitEvent = async () => {
  const $table = xTable.value;
  const $form = xForm.value;
  const errMap = await $form.validate();
  if (!errMap) {
    procedure.submitLoading = true;
    if (procedure.selectRow) {
      // 修改
      updateQualityInItem(procedure.formData)
        .then((res: any) => {
          if (res.code === 0) {
            Object.assign(procedure.selectRow, procedure.formData);
            successMessage("保存成功");
            procedure.showEdit = false;
          } else {
            errorMessage(res.message);
          }
          procedure.submitLoading = false;
        })
        .catch(() => {
          errorMessage("操作失败");
          procedure.submitLoading = false;
        });
    } else {
      // 新增
      addQualityInItem(procedure.formData)
        .then((res: any) => {
          if (res.code === 0) {
            searchEvent();
            successMessage("新增成功");
            procedure.showEdit = false;
          } else {
            errorMessage(res.message);
          }
          procedure.submitLoading = false;
        })
        .catch(() => {
          errorMessage("操作失败");
          procedure.submitLoading = false;
        });
    }
  }
};

const handleClose = () => {
  nextTick(() => {
    procedure.showEdit = false;
  });
};
// 根据查询条件导出数据
const download = () => {
  downloadTemplete()
    .then((res: any) => {
      if (res.code == 500) {
        errorMessage(res.message);
      } else {
        const fileBlob = res;
        const fileUrl = URL.createObjectURL(fileBlob); //将blob转成url地址
        const element = document.createElement("a");
        element.setAttribute("href", fileUrl);
        element.setAttribute("downLoad", "质检项模板.xls");
        document.body.appendChild(element);
        element.click();
        document.body.removeChild(element);
      }
    })
    .catch(() => {
      errorMessage("操作失败");
    });
};
// 文件上传关闭
const uploadExcelClose = () => {
  searchEvent();
};
// mounted
onMounted(() => {
  nextTick(() => {
    searchEvent();
    table.tableHeight = changeHeight();
  });
});
</script>

<template>
  <div>
    <!-- 工具栏 -->
    <vxe-form :data="table.listQuery">
      <vxe-form-item title="检查项目" field="filterName" :item-render="{}">
        <template #default="{ data }">
          <vxe-input
            v-model="data.filterName"
            placeholder="请输入检查项目"
          ></vxe-input>
        </template>
      </vxe-form-item>
      <vxe-form-item>
        <template #default>
          <vxe-button
            icon="fa fa-search"
            status="primary"
            @click="searchEvent"
            v-auth="routeName + ':search'"
            >查询</vxe-button
          >
          <vxe-button
            icon="fa fa-plus"
            status="primary"
            @click="insertEvent"
            v-auth="routeName + ':add'"
            >新增</vxe-button
          >
          <vxe-button
            status="primary"
            icon="fa fa-download"
            v-auth="routeName + ':download'"
            @click="download"
            >下载模板</vxe-button
          >
          <upload-excel
            downLoadUrl="/quality-in-item/upload"
            @uploadExcelClose="uploadExcelClose"
          ></upload-excel>
        </template>
      </vxe-form-item>
    </vxe-form>
    <!-- 列表 -->
    <vxe-table
      ref="xTable"
      class="mytable-style"
      border
      show-header-overflow
      show-overflow
      :row-config="{ isHover: true }"
      :print-config="{}"
      :export-config="{}"
      :height="table.tableHeight"
      :data="table.tableData"
    >
      <vxe-column type="seq" title="序号" width="60"></vxe-column>
      <vxe-column field="name" title="检查项目" min-width="120"></vxe-column>
      <vxe-column
        field="standard"
        title="技术要求"
        min-width="150"
      ></vxe-column>
      <vxe-column
        field="measureTools"
        title="测量工具"
        min-width="120"
      ></vxe-column>
      <vxe-column field="specificity" title="精度" min-width="120"></vxe-column>
      <vxe-column
        field="recordForm"
        title="记录形式"
        min-width="120"
      ></vxe-column>
      <vxe-column field="createdBy" title="创建人" min-width="100"></vxe-column>
      <vxe-column field="createdTime" title="创建时间" min-width="100">
        <template #default="{ row }">
          {{ row.createdTime ? row.createdTime.split(" ")[0] : "" }}
        </template>
      </vxe-column>
      <vxe-column field="qiTest" title="是否需要专检" min-width="120">
        <template #default="{ row }">
          <el-tag type="success" v-if="row.qiTest == 1">是</el-tag>
          <el-tag type="danger" v-if="row.qiTest == 2">否</el-tag>
        </template>
      </vxe-column>
      <vxe-column field="selfTest" title="是否需要自检" min-width="120">
        <template #default="{ row }">
          <el-tag type="success" v-if="row.selfTest == 1">是</el-tag>
          <el-tag type="danger" v-if="row.selfTest == 2">否</el-tag>
        </template>
      </vxe-column>
      <vxe-column field="isEnabled" title="状态" min-width="90">
        <template #default="{ row }">
          <el-tag type="success" v-if="row.isEnabled == 1">已启用</el-tag>
          <el-tag type="danger" v-if="row.isEnabled == 0">已禁用</el-tag>
        </template>
      </vxe-column>
      <vxe-column title="操作" width="150" fixed="right">
        <template #default="{ row }">
          <vxe-button
            type="text"
            icon="fa fa-edit"
            @click="editEvent(row)"
            v-auth="routeName + ':edit'"
            >编辑</vxe-button
          >
          <vxe-button
            v-if="row.isEnabled == 1"
            type="text"
            icon="fa fa-close"
            @click="disableEvent(row)"
            v-auth="routeName + ':disable'"
            >禁用</vxe-button
          >
          <vxe-button
            v-if="row.isEnabled == 0"
            type="text"
            icon="fa fa-check"
            @click="disableEvent(row)"
            v-auth="routeName + ':disable'"
            >启用</vxe-button
          >
        </template>
      </vxe-column>
    </vxe-table>

    <!-- 分页 -->
    <vxe-pager
      perfect
      @page-change="handlePageChange"
      v-model:current-page="page.pageNum"
      v-model:page-size="page.pageRow"
      :total="page.totalResult"
      :page-sizes="[10, 20, 50, 100, 300]"
      :layouts="[
        'PrevJump',
        'PrevPage',
        'Number',
        'NextPage',
        'NextJump',
        'Sizes',
        'FullJump',
        'Total'
      ]"
    >
    </vxe-pager>
    <!-- 表单弹框 -->
    <vxe-modal
      v-model="procedure.showEdit"
      :title="procedure.selectRow ? '编辑&保存' : '新增&保存'"
      width="400"
      min-width="400"
      min-height="600"
      :loading="procedure.submitLoading"
      resize
      showFooter
      destroy-on-close
      @close="handleClose"
    >
      <template #default>
        <vxe-form
          ref="xForm"
          :data="procedure.formData"
          :rules="procedure.formRules"
          title-align="right"
          title-width="100"
        >
          <vxe-form-item
            field="name"
            title="检查项目"
            :span="24"
            :item-render="{}"
          >
            <template #default="{ data }">
              <vxe-input
                v-model="data.name"
                placeholder="请输入检查项目"
              ></vxe-input>
            </template>
          </vxe-form-item>
          <vxe-form-item
            field="standard"
            title="技术要求"
            :span="24"
            :item-render="{}"
          >
            <template #default="{ data }">
              <vxe-input
                v-model="data.standard"
                placeholder="请输入技术要求"
              ></vxe-input>
            </template>
          </vxe-form-item>
          <vxe-form-item
            field="measureTools"
            title="测量工具"
            :span="24"
            :item-render="{}"
          >
            <template #default="{ data }">
              <vxe-input
                v-model="data.measureTools"
                placeholder="请输入测量工具"
              ></vxe-input>
            </template>
          </vxe-form-item>
          <vxe-form-item
            field="specificity"
            title="精度"
            :span="24"
            :item-render="{}"
          >
            <template #default="{ data }">
              <vxe-input
                v-model="data.specificity"
                placeholder="请输入精度"
              ></vxe-input>
            </template>
          </vxe-form-item>
          <vxe-form-item
            field="recordForm"
            title="记录形式"
            :span="24"
            :item-render="{}"
          >
            <template #default="{ data }">
              <vxe-input
                v-model="data.recordForm"
                placeholder="请输入记录形式"
              ></vxe-input>
            </template>
          </vxe-form-item>
          <vxe-form-item field="qiTest" title="是否需要专检" :span="24">
            <template #default="{ data }">
              <el-radio-group v-model="data.qiTest">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="2">否</el-radio>
              </el-radio-group>
            </template>
          </vxe-form-item>
          <vxe-form-item field="selfTest" title="是否需要自检" :span="24">
            <template #default="{ data }">
              <el-radio-group v-model="data.selfTest">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="2">否</el-radio>
              </el-radio-group>
            </template>
          </vxe-form-item>
        </vxe-form>
      </template>
      <template #footer>
        <vxe-button @click="handleClose">取 消</vxe-button>
        <vxe-button status="primary" @click="submitEvent">确 定</vxe-button>
      </template>
    </vxe-modal>
  </div>
</template>
<style>
.mytable-style .vxe-body--column.col-blue {
  background-color: #60b8ff;
  color: #fff;
}
.mytable-style .vxe-body--column.col-orange {
  background-color: #f56c6c;
  color: #fff;
}
</style>
<style lang="scss" scoped>
.vxe-input + .vxe-button,
.vxe-input + .vxe-button--dropdown,
.vxe-button + .vxe-button,
.vxe-button + .vxe-button--dropdown {
  margin-left: 0;
}

.vxe-toolbar.size--medium {
  padding: 10px;
}

.vxe-table--render-default.size--medium {
  margin-top: 12px;
}

.vxe-button.size--medium.type--button {
  margin-left: 1em;
  height: 32px;
}

.text-model {
  &:hover {
    cursor: pointer;
  }
}
</style>
